package com.ishare.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ishare.admin.mapper.SysUserMapper;
import com.ishare.admin.service.SysRoleService;
import com.ishare.admin.service.SysUserRoleService;
import com.ishare.admin.service.SysUserService;
import com.ishare.common.entity.dto.SysUserDto;
import com.ishare.common.entity.po.SysUser;
import com.ishare.common.exception.BusinessException;
import com.ishare.common.page.PageUtils;
import com.ishare.common.utils.BeanUtils;
import com.ishare.common.utils.Query;
import com.ishare.common.utils.RandomStringUtil;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 * @author Mark sunlightcs@gmail.com
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String account = (String) params.get("account");
        Long createBy = (Long) params.get("createBy");

        IPage<SysUser> page = this.page(
            new Query<SysUser>().getPage(params),
            new QueryWrapper<SysUser>()
                .like(StringUtils.isNotBlank(account), "account", account)
                .eq(createBy != null, "create_by", createBy)
        );

        return new PageUtils(page);
    }

    @Override
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public SysUser queryByAccount(String account) {
        return baseMapper.queryByAccount(account);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUserDto user) {
        //sha256加密
        String salt = RandomStringUtil.randomAlphanumeric(20);
        user.setPwd(new Sha256Hash(user.getPwd(), salt).toHex());
        user.setSalt(salt);
        user.setStatus(1);
        this.save(user);
        //检查角色是否越权
        checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserDto user) {
        if (!StringUtils.isBlank(user.getPwd())) {
            String salt = RandomStringUtil.randomAlphanumeric(20);
            user.setSalt(salt);
            user.setPwd(new Sha256Hash(user.getPwd(),salt).toHex());
        }
        boolean update = this.updateById(user);
        if (!update){
            throw new BusinessException("修改失败！");
        }
        //检查角色是否越权
        checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] userId) {
        this.removeByIds(Arrays.asList(userId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUser userEntity = new SysUser();
        userEntity.setPwd(newPassword);
        return this.update(userEntity,
            new QueryWrapper<SysUser>().eq("user_id", userId).eq("password", password));
    }

    @Override
    public SysUser selectById(Long userId) {
        return baseMapper.selectById(userId);
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUser user) {
        /*if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
            return;
        }
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (user.getCreateUserId() ==1) {
            return;
        }

        //查询用户创建的角色列表
        List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

        //判断是否越权
        if (!roleIdList.containsAll(user.getRoleIdList())) {
            throw new BusinessException("新增用户所选角色，不是本人创建");
        }*/
    }
}
